package com.kuqi.blog.handler;

import com.alibaba.fastjson.JSON;
import com.kuqi.blog.dao.pojo.SysUser;
import com.kuqi.blog.service.SysUserService;
import com.kuqi.blog.util.UserThreadLocal;
import com.kuqi.blog.vo.ErrorCode;
import com.kuqi.blog.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author:kuqi
 * @createTime:2021/12/15 19:10
 * @description:登录拦截器
 */

@Component   //spring注解，该类交给spring容器管理
@Slf4j
public class LoginInterceptor  implements HandlerInterceptor {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 在执行controller方法接口之前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 1.需要判断请求的接口路劲是否为HandlerMethod(Controller方法)
         * 2.判断token是否为空，如果为空 未登录
         * 3.如果token 不为空，登录验证，SysUserService checkToken
         * 4.如果认证成功，放行即可
         */

        //1.判断是否是访问的resources文件,是的话放行
        if (!(handler instanceof HandlerMethod)){
            //handler可能是RequestRecourseHandler springboot程序访问的静态资源
            return true;
        }

        //2.判断token是否为空
        String token = request.getHeader("Authorization");

        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}",requestURI);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");

        if (StringUtils.isBlank(token)){
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
            //设置浏览器能够识别的数据格式是json
            response.setContentType("application/json;charset=utf-8");
            //alibaba的fastJson工具将对象转换成json字符串
            response.getWriter().print(JSON.toJSONString(result));
            return  false;
        }


        //3.验证token
        SysUser sysUser = sysUserService.checkToken(token);
        if (sysUser  == null){
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), "未登录");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
        }

        //是登录状态放行
        //希望在controller中直接获取用户的信息，利用本地线程获取
        UserThreadLocal.put(sysUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //如果不删除ThreadLocal中用完的信息，会有内存泄露的风险
        UserThreadLocal.remove();
    }
}
